home *** CD-ROM | disk | FTP | other *** search
- Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
- From: gzhjis@ubszh.net.ch (Ian Johnston (by ubsswop))
- Newsgroups: comp.lang.c++
- Subject: Re: Advanced C++ question...
- Date: 21 Mar 1996 09:17:26 GMT
- Organization: UBS
- Distribution: world
- Message-ID: <4ir6r6$qoa@ubszh.fh.zh.ubs.com>
- References: <4iprfg$1ui@aadt>
- NNTP-Posting-Host: nol2179.fh.zh.ubs.com
-
- In article <4iprfg$1ui@aadt>, david_hooker@sdt.com writes:
- |> Hi all...
- |>
- |> I want to write an operator* for a class, but I want to do
- |> one of 2 things:
- |> 1. Call one of two different operator*'s depending on whether
- |> it is an lvalue or rvalue
- |> OR
- |> 2. Somehow determine in the function if it is being used as an
- |> lvalue or an rvalue.
- |>
- |> For instance, I want to know, in the operator*, from which case I'm
- |> being called:
- |>
- |> *Object = SomeValue; // used as an lvalue
- |>
- |> SomeValue = *Object; // used as an rvalue
-
- Instead of your operator * returning a reference to the object, have it
- return an instance of a helper class. This helper class has operator =
- and operator T. For example:
-
-
- class ThingRef;
-
- class Thing
- {
- public:
- // Usual members...
- ThingRef operator *();
- };
-
-
- class ThingRef
- {
- public:
- ThingRef(Thing &t);
- void operator = (Thing const &value);
- operator Thing &();
-
- private:
- Thing &ref;
- };
-
-
- ThingRef Thing::operator *()
- {
- return ThingRef(*this);
- }
-
-
- ThingRef::ThingRef(Thing &t)
- : ref(t)
- {
- }
-
- void ThingRef::operator = (Thing const &value)
- {
- // Use as an lvalue.
- ref = value;
- }
-
- ThingRef::operator Thing &()
- {
- // Use as an rvalue.
- return ref;
- }
-
-
- Inlining the ThingRef class may help if you find there is a performance
- hit here.
-
- Ian
-